package com.hzit.cart.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.hzit.cart.api.domain.Order;
import com.hzit.cart.api.domain.PayAsyncVo;
import com.hzit.cart.api.domain.PayLog;
import com.hzit.cart.config.PayProperties;
import com.hzit.cart.service.IOrderService;
import com.hzit.cart.service.IPayLogService;
import com.hzit.cart.service.PayService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Service
public class PayServiceImpl implements PayService {
	@Autowired
	private PayProperties properties;
	@Autowired
	private IPayLogService payLogService;
	@Autowired
	private IOrderService orderService;
	//1. 支付宝异步回调支付
	@Override
	public String asyncNotify(Map<String, String> params, PayAsyncVo vo) throws AlipayApiException {
		//2.1 进行验签操作
		boolean signVerified = AlipaySignature.rsaCheckV1(params, properties.getAlipay_public_key(),
				properties.getCharset(), properties.getSign_type()); //调用SDK验证签名
		//2.2  执行我们自己的业务操作
		if(signVerified){   // 如果验签成功
			String trade_status = vo.getTrade_status();
			//2.2.1 支付成功,就更新支付日志，并更新订单状态
			if("TRADE_FINISHED".equals(trade_status) || "TRADE_SUCCESS".equals(trade_status)){
				//2.2.2 得到商户订单号
				String out_trade_no = vo.getOut_trade_no();
				//2.2.3 根据订单号查询出订单
				PayLog payLog = payLogService.getById(out_trade_no);
				//2.2.4 修改支付日志
				payLog.setTradeState("1");                  // 代表己支付
				payLog.setTransactionId(vo.getTrade_no());  // 设置流水号
				payLog.setPayTime(LocalDateTime.now());     // 支付时间
				//2.2.5 修改支付日志
				payLogService.updateById(payLog);

				//2.2.6 得到订单id列表
				String ids = payLog.getOrderList();
				String[] split = ids.split(",");
				for (String id : split) {
					Order order = new Order();
					order.setStatus("2");
					order.setOrderId(Long.parseLong(id.trim()));
					orderService.updateById(order);
				}
				return "success";
			}
		}
		return "fail";
	}
}
